﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.IO;
using EKETEAM.Data;
using EKETEAM.FrameWork;
using System.Xml;


namespace eFrameWork.Manage
{
    public partial class CompareOnline : System.Web.UI.Page
    {
        public string pattern = "";
        string serverUrl = "http://frame.eketeam.com/Services/databaseSchema.aspx";
        //string filepath = "columns_cache.xml";
        string filepath = "../upload/temp/columns_cache.xml";
        protected void Page_Load(object sender, EventArgs e)
        {
            pattern = eParameters.Request("pattern");
            if (pattern.Length == 0) pattern = "1";
            string act = eParameters.QueryString("act");
            switch (act)
            {
                case "": 
                    list();
                    break;
                case "add":
                    add();
                    break;
                case "create":
                    create();
                    break;
            }            
        }
        private void checkFile()
        {
            string path = Server.MapPath(filepath);
            if (!Directory.Exists(new eFileInfo(path).Path)) Directory.CreateDirectory(new eFileInfo(path).Path);
            if (System.IO.File.Exists(path))
            {
                FileInfo fi = new FileInfo(path);
                TimeSpan timeSpan = DateTime.Now - fi.CreationTime;
                int Minutes = Convert.ToInt32(timeSpan.TotalMinutes);
                if (Minutes < 31) return;
            }
            string xmlbody = eBase.getRequest(serverUrl);
            if (xmlbody.StartsWith("<") && xmlbody.EndsWith(">"))
            {
                eBase.WriteFile(path, xmlbody);
            }
        }
        private void add()
        {
            string table = eParameters.QueryString("table");
            string code = eParameters.QueryString("code");
            string path = Server.MapPath(filepath);
            if (!Directory.Exists(new eFileInfo(path).Path)) Directory.CreateDirectory(new eFileInfo(path).Path);
            if (System.IO.File.Exists(path))
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(path);
                XmlNode node = doc.SelectSingleNode("/root/model");
                if (node != null)
                {
                    XmlNode onode = node.SelectSingleNode("table[translate(@name,'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz')='" + table.ToLower() + "']");//不区分大小写
                    if (onode != null)
                    {
                      
                        DataTable dt = onode.ChildNodes.toDataTable();
                        DataRow[] rows = dt.Select("COLUMN_NAME='" + code + "'");
                        if (rows.Length > 0)
                        {
                            //eBase.Writeln(table + "::" + code);
                            //eBase.PrintDataRow(rows);
                            eBase.DataBase.addSchemaColumn(table, rows[0]);
                        }
                    }
                }
            }
            string ajax = eParameters.QueryString("ajax");
            if (ajax == "true")
            {
                Response.End();
               
            }
            else
            {
                Response.Redirect(eBase.getAspxFileName(), true);
            }
        }
        private void create()
        {
            string table = eParameters.QueryString("table");
            string path = Server.MapPath(filepath);
            if (!Directory.Exists(new eFileInfo(path).Path)) Directory.CreateDirectory(new eFileInfo(path).Path);
            if (System.IO.File.Exists(path))
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(path);
                XmlNode node = doc.SelectSingleNode("/root/model");
                if (node != null)
                {
                    XmlNode onode = node.SelectSingleNode("table[translate(@name,'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz')='" + table.ToLower() + "']");//不区分大小写
                    if (onode != null)
                    {
                        DataTable dt = onode.ChildNodes.toDataTable();
                        //eBase.PrintDataTable(dt);
                        eBase.DataBase.SchemaCreate(dt);
                    }
                }
            }
            string ajax = eParameters.QueryString("ajax");
            if (ajax == "true")
            {
                Response.End();

            }
            else
            {
                Response.Redirect(eBase.getAspxFileName(), true);
            } 
        }
        private void list()
        {
            checkFile();
            string path = Server.MapPath(filepath);
            if (!Directory.Exists(new eFileInfo(path).Path)) Directory.CreateDirectory(new eFileInfo(path).Path);
            if (System.IO.File.Exists(path))
            {
                StringBuilder sb = new StringBuilder();
                StringBuilder sbl = new StringBuilder();
                StringBuilder sbr = new StringBuilder();

                DataTable tb = eBase.DataBase.getSchemaTables();
                XmlDocument doc = new XmlDocument();
                doc.Load(path);
                XmlNode node = doc.SelectSingleNode("/root/model");
                foreach (XmlNode _node in node.ChildNodes)
                {
                    string name = _node.Attributes["name"].Value;
                    DataTable dt1 = _node.ChildNodes.toDataTable();
                    sbl.Append("<div class=\"close\" onclick=\"show(this);\">" + name + "</div>");
                    sbl.Append("<ul style=\"display:none;margin-left:40px;\">\r\n");
                    foreach (DataRow dr in dt1.Rows)
                    {
                        sbl.Append("<li>" + dr["COLUMN_NAME"].ToString() + "</li>");
                    }
                    sbl.Append("</ul>\r\n");




                    DataRow[] rows = tb.Select("value='" + name + "'");
                    bool has = rows.Length == 0 ? false : true;


                    DataTable dt2 = has ? eBase.DataBase.getSchemaColumns(name) : dt1.Clone();//当前结构
                    bool changed = false;
                    if (dt1.Rows.Count == dt2.Rows.Count)
                    {
                        foreach (DataRow _dr in dt1.Rows)
                        {
                            DataRow[] _rs = new DataTable().Select();
                            if (pattern == "2")//详细
                            {
                                _rs = dt2.Select("COLUMN_NAME='" + _dr["COLUMN_NAME"].ToString() + "' and DATA_TYPE='" + _dr["DATA_TYPE"].ToString() + "' and CHARACTER_MAXIMUM_LENGTH='" + _dr["CHARACTER_MAXIMUM_LENGTH"].ToString() + "'");
                            }
                            else
                            {
                                _rs = dt2.Select("COLUMN_NAME='" + _dr["COLUMN_NAME"].ToString() + "' and DATA_TYPE='" + _dr["DATA_TYPE"].ToString() + "'");
                            }
                            if (_rs.Length == 0)
                            {
                                changed = true;
                                break;
                            }
                            else
                            {
                                if (_dr["COLUMN_DEFAULT"].ToString() != _rs[0]["COLUMN_DEFAULT"].ToString() && pattern == "2")
                                {
                                    changed = true;
                                    break;
                                }
                            }
                        }
                    }
                    else
                    {
                        changed = true;
                    }


                    sbr.Append("<div class=\"close\"" + (rows.Length == 0 || changed ? " style=\"color:#ff0000;\"" : "") + " onclick=\"show(this);\">" + name + (has ? "" : "<a href=\"javascript:;\" onclick=\"createTable(this,'" + name + "');\" _href=\"?act=create&table=" + name + "\" style=\"display:inline-block;margin-left:20px;\">同步</a>") + "</div>");
                    sbr.Append("<ul style=\"display:none;margin-left:40px;\">\r\n");
                    foreach (DataRow _dr in dt1.Rows)
                    {
                        changed = false;
                        bool _has = dt2.Select("COLUMN_NAME='" + _dr["COLUMN_NAME"].ToString() + "'").Length == 0 ? false : true;
                        DataRow[] _rs = new DataTable().Select();
                        if (pattern == "2")//详细
                        {
                            _rs = dt2.Select("COLUMN_NAME='" + _dr["COLUMN_NAME"].ToString() + "' and DATA_TYPE='" + _dr["DATA_TYPE"].ToString() + "' and CHARACTER_MAXIMUM_LENGTH='" + _dr["CHARACTER_MAXIMUM_LENGTH"].ToString() + "'");
                        }
                        else
                        {
                            _rs = dt2.Select("COLUMN_NAME='" + _dr["COLUMN_NAME"].ToString() + "' and DATA_TYPE='" + _dr["DATA_TYPE"].ToString() + "'");
                        }
                        if (_rs.Length == 0)
                        {
                            changed = true;
                        }
                        else
                        {
                            if (_dr["COLUMN_DEFAULT"].ToString() != _rs[0]["COLUMN_DEFAULT"].ToString() && pattern == "2")
                            {
                                changed = true;
                            }
                        }

                        sbr.Append("<li" + (changed ? " style=\"color:#ff0000;\"" : "") + ">" + _dr["COLUMN_NAME"].ToString() + (has && !_has ? "<a href=\"javascript:;\" onclick=\"addField(this,'" + name + "','" + _dr["COLUMN_NAME"].ToString() + "');\" _href=\"?act=add&table=" + name + "&code=" + _dr["COLUMN_NAME"].ToString() + "\" style=\"display:inline-block;margin-left:20px;\">同步</a>" : "") + "</li>");
                    }
                    sbr.Append("</ul>\r\n");
                }

               
                sb.Append("<table width=\"600\" border=\"0\" cellspacing=\"1\" cellpadding=\"0\" bgcolor=\"#CCCCCC\" clas1s=\"eDataTable\" style=\"margin-top:10px;\">\r\n");
                sb.Append("<thead>\r\n");
                sb.Append("<tr bgcolor=\"#f2f2f2\">\r\n");
                sb.Append("<td>最新结构</td>\r\n");
                sb.Append("<td>当前结构</td>\r\n");
                sb.Append("</tr>\r\n");
                sb.Append("</thead>\r\n");
                sb.Append("<tbody>\r\n");
                sb.Append("<tr valign=\"top\" bgcolor=\"#ffffff\">\r\n");
                sb.Append("<td heigh1t=\"25\">\r\n");
                sb.Append(sbl.ToString());
                sb.Append("</td>\r\n");
                sb.Append("<td>\r\n");
                sb.Append(sbr.ToString());
                sb.Append("</td>\r\n");
                sb.Append("</tr>\r\n");
                sb.Append("</tbody>\r\n");
                sb.Append("</table>\r\n");               

                LitBody.Text = sb.ToString();
            }
        }
        protected void Page_PreRender(object sender, EventArgs e)
        {
            if (Master == null) return;
            Literal lit = (Literal)Master.FindControl("LitTitle");
            if (lit != null)
            {
                lit.Text = "库对比(在线) - " + eConfig.manageName();
            }
        }
    }
}